/* 
 * File:   Repeat.cpp
 * Author: maximiliano
 * 
 * Created on March 26, 2013, 5:43 PM
 */

#include "Repeat.h"

using namespace TP3::Mangling;

Repeat::Repeat(int posIni, int posEnd, int times, int posInsert) {
    
    _posIni = posIni;
    _posEnd = posEnd;
    _times = times;
    _posInsert = posInsert;
    
}

Repeat::~Repeat() {
}

string& Repeat::run (string& operating){
    
    // Obtengo el substring.
    
    string substring = "";
    
    long int posIni = _posIni;
    if (_posIni < 0)
        posIni = operating.length() + _posIni;
    
    long int posEnd = _posEnd;    
    if (_posEnd < 0)
        posEnd = operating.length() + _posEnd;    
    
    if (0 <= posIni && posIni <= posEnd && posEnd < (long int)operating.length() && (posEnd - posIni) >= 0)
        substring = operating.substr(posIni, posEnd-posIni + 1);

    // Repito el string 
    
    for (int c = 1; c < _times; c++)
        substring += substring;
    
    // Calculo la posicion donde insertar el substring.
    
    long int posInsert = operating.length() + _posInsert + 1;
    
    if (posInsert < 0)
        operating = substring + operating;
    
    else if (0 <= posInsert && posInsert < (long int) operating.length())
        operating = operating.insert(posInsert, substring);
    else
        operating = operating + substring;
    
    return operating;
}


string Repeat::getName(){

    return "repeat";
}